using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace SmartContentUI.Query
{
    public partial class Grid : UserControl
    {
        #region Variables
        private SmartContentBusiness.Session ses;

        private Util.EXComboBox boolCombo;
        private ImageList imglst;
        private SmartContentDB.Interfaces.Field[] column;
        private string table;
        private int tableId;

        public delegate void PropChanged(string creator, bool locked);
        public event PropChanged PropChange;
        public delegate void OpenItem(int id, string[] values, bool visible, bool editable, bool exportanble, bool printable);
        public event OpenItem Open;
        #endregion

        #region Constructor
        public Grid(SmartContentBusiness.Session ses, string table, int tableId)
        {
            InitializeComponent();
            this.ses = ses;
            initCombo();
            this.table = table;
            this.tableId = tableId;
        }
        #endregion

        #region Functions
        private void initCombo()
        {
            imglst = new ImageList();
            imglst.ColorDepth = ColorDepth.Depth32Bit;
            imglst.Images.Add(global::SmartContentUI.Properties.Resources._true);
            imglst.Images.Add(global::SmartContentUI.Properties.Resources._false);
            boolCombo = new Util.EXComboBox();
            boolCombo.Items.Add(new Util.EXComboBox.EXImageItem(imglst.Images[0], "1"));
            boolCombo.Items.Add(new Util.EXComboBox.EXImageItem(imglst.Images[1], "0"));
            boolCombo.DropDownStyle = ComboBoxStyle.DropDownList;
        }

        public void executeQuery(SmartContentDB.Interfaces.Field[] column, Boolean filter)
        {
            this.column = column;
            if(!filter) createColumnHeader(column);
            fillRows();
            ses.releaseQuery();
        }

        public void reload()
        {
            ses.executeQuery(table, tableId, "1 = 1");
            fillRows();
            ses.releaseQuery();
        }

        public void deleteDocument()
        {
            if (exListView1.SelectedItems.Count == 0)
            {
                MessageBox.Show("Debe seleccionar al menos un documento", "Borrado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                if (MessageBox.Show("Seguro que desea eliminar el documento?", "Borrado", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    Util.EXListViewItem item = (Util.EXListViewItem)exListView1.SelectedItems[0];
                    try
                    {
                        this.ses.delDocument(table,tableId, item.Id.ToString());
                        MessageBox.Show("Documento borrado satisfactoriamente", "Borrado", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        reload();
                    }
                    catch(Exception e)
                    {
                        MessageBox.Show("Imposible borrar documento: " + e.Message, "Borrado", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        #region Fabian
        public SmartContentDB.Interfaces.Field[] getDocument()
        {
            int numCampos = this.exListView1.Columns.Count;
            SmartContentDB.Interfaces.Field[] campos = new SmartContentDB.Interfaces.Field[numCampos];
            //TODO llenar campos
            return campos;
        }
        #endregion

        private void createColumnHeader(SmartContentDB.Interfaces.Field[] column)
        {
            Util.EXEditableColumnHeader colString;
            Util.EXEditableColumnHeader colBool;
            int colWidth = (this.exListView1.Width / column.Length) - 1;
            if (colWidth < 90)
                colWidth = 90;
            for (int i = 0; i < column.Length; i++)
            {
                if (column[i].getType().ToUpper().Equals("TINYINT"))
                {
                    colBool = new Util.EXEditableColumnHeader(column[i].getName(), boolCombo);
                    colBool.TextAlign = HorizontalAlignment.Center;
                    colBool.Width = colWidth;
                    this.exListView1.Columns.Add(colBool);
                }
                else
                {
                    colString = new Util.EXEditableColumnHeader(column[i].getName());
                    colString.Width = colWidth;
                    colString.TextAlign = HorizontalAlignment.Center;
                    this.exListView1.Columns.Add(colString);
                }
            }
        }

        private void addlFilterRow()
        {
            Util.EXListViewItem item = null;
            for (int i = 0; i < column.Length; i++)
            {
                if (column[i].getType().ToUpper().Equals("TINYINT"))
                {
                    item.SubItems.Add(new Util.EXImageListViewSubItem());
                }
                else
                {
                    if (item == null)
                    {
                        item = new Util.EXListViewItem("*");
                        item.Editable = true;
                    }
                    else
                    {
                        item.SubItems.Add("*");
                    }
                }
            }
            item.Id = -1;
            this.exListView1.Items.Add(item);
        }

        private void fillRows()
        {
            exListView1.Items.Clear();
            addlFilterRow();
            for (int top = 0; top < 30; top++)
            {
                SmartContentDB.Interfaces.Document doc = ses.getRow(this.column);
                if (doc == null)
                    break;
                Util.EXListViewItem item = new Util.EXListViewItem();
                for (int i = 0; i < doc.Fields.Length; i++)
                {
                    if (i == 0)
                    {
                        item.Text = doc.Fields[i];
                        item.SubItems[item.SubItems.Count - 1].Tag = doc.Fields[i];
                    }
                    else
                    {
                        if (((Util.EXEditableColumnHeader)exListView1.Columns[i]).MyControl != null)
                        {
                            if (doc.Fields[i].Equals("1") || doc.Fields[i].ToLower().Equals("true"))
                            {
                                item.SubItems.Add(new Util.EXMultipleImagesListViewSubItem(new ArrayList(new object[] { imglst.Images[0] }), "1"));
                                item.SubItems[item.SubItems.Count - 1].Tag = "1";
                            }
                            else
                            {                                
                                item.SubItems.Add(new Util.EXMultipleImagesListViewSubItem(new ArrayList(new object[] { imglst.Images[1] }), "0"));
                                item.SubItems[item.SubItems.Count - 1].Tag = "0";
                            }
                        }
                        else
                        {
                            item.SubItems.Add(doc.Fields[i]);
                            item.SubItems[item.SubItems.Count - 1].Tag = doc.Fields[i];
                        }
                    }
                }
                item.Editable = false;
                item.Id = doc.getId();
                item.Creator = doc.getCreator();
                item.IsLock = !doc.isEditable();
                item.IsVisible = doc.isVisible();
                item.IsExportable = doc.isExportable();
                item.IsPrintable = doc.isPrintable();

                this.exListView1.Items.Add(item);
            }
        }

        public String getTable() {
            return this.table;
        }

        public int getTableId() {
            return this.tableId;
        }
        #endregion

        #region Events
        private void exListView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (exListView1.SelectedItems.Count > 0)
            {
                Util.EXListViewItem item = (Util.EXListViewItem)exListView1.SelectedItems[0];
                PropChange(item.Creator, item.IsLock);
            }
        }

        private void exListView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (exListView1.SelectedItems.Count > 0)
            {
                Util.EXListViewItem item = (Util.EXListViewItem)exListView1.SelectedItems[0];
                if (item.Id != -1)
                {
                    if (!item.IsVisible)
                    {
                        MessageBox.Show("No tiene derechos para ver este documento", "Acceso restringido", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }
                    ArrayList valueList = new ArrayList();
                    for (int i = 0; i < column.Length; i++)
                    {
                        if (column[i].getType().ToUpper().Equals("TINYINT"))
                            valueList.Add(((Util.EXMultipleImagesListViewSubItem)item.SubItems[i]).MyValue);
                        else
                            valueList.Add(item.SubItems[i].Text);
                    }
                    string[] values = new string[valueList.Count];
                    valueList.CopyTo(values);
                    Open(item.Id, values, item.IsVisible, item.IsLock, item.IsExportable, item.IsPrintable);
                }
            }
        }

        private void exListView1_ItemChange(object sender)
        {
            string valor, filtro;
            filtro = "1 = 1";
            for (int i = 0; i < column.Length; i++)
            {
                if (column[i].getType().ToUpper().Equals("TINYINT"))
                {
                    Util.EXImageListViewSubItem item = (Util.EXImageListViewSubItem)exListView1.Items[0].SubItems[i];
                    valor = item.MyValue;
                }
                else
                    valor = exListView1.Items[0].SubItems[i].Text;
                if (valor != "*" && valor != "")
                {
                    if (column[i].getType().ToUpper().Equals("VARCHAR"))
                        filtro += " AND `" + exListView1.Columns[i].Text + "` like '%" + valor + "%'";
                    else if (column[i].getType().ToUpper().IndexOf("DATE") != -1)
                        filtro += " AND `" + exListView1.Columns[i].Text + "` = '" + valor + "'";
                    else
                        filtro += " AND `" + exListView1.Columns[i].Text + "` = " + valor;
                }
            }
            ses.executeQuery(table, tableId, filtro);
            fillRows();
            ses.releaseQuery();
        }
        public string[] getValues()
        {
            string[] values = null;
            Util.EXListViewItem item = (Util.EXListViewItem)exListView1.SelectedItems[0];
            if (item.Id != -1)
            {
                if (!item.IsVisible)
                {
                    MessageBox.Show("No tiene derechos para ver este documento", "Acceso restringido", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return values;
                }
                ArrayList valueList = new ArrayList();
                for (int i = 0; i < column.Length; i++)
                {
                    if (column[i].getType().ToUpper().Equals("TINYINT"))
                        valueList.Add(((Util.EXMultipleImagesListViewSubItem)item.SubItems[i]).MyValue);
                    else
                        valueList.Add(item.SubItems[i].Text);
                }
                values = new string[valueList.Count];
                valueList.CopyTo(values);
                //Open(item.Id, values, item.IsVisible, item.IsLock, item.IsExportable, item.IsPrintable);
            }
            return values;
        }

        public int getRegistryId()
        {
            Util.EXListViewItem item = (Util.EXListViewItem)exListView1.SelectedItems[0];
            return item.Id;
        }
        #endregion

    }
}
